<template>
  <div id="product">
    <dialogProduct @close="closeDialog" v-if="show" @addProduct="getSelProductList"></dialogProduct> 
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="*选择产品">
        <el-radio-group v-model="form.productType">
          <el-radio label="ANY" :disabled="status==1">所有固收类产品</el-radio>
          <el-radio label="ASSIGN" :disabled="status==1">指定产品</el-radio>
        </el-radio-group>
        <el-button @click="show=!show" v-if="form.productType=='ASSIGN'" style="margin-left:15px">选择产品</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="selectedProducts"  v-if="form.productType=='ASSIGN'">
        <el-table-column type="index"        label="序号" width="80"></el-table-column>
        <el-table-column prop="name"         label="产品名称" min-width="140"></el-table-column>
        <el-table-column prop="issuerName"   label="发行方" min-width="60"></el-table-column>
        <el-table-column prop="account"      label="募集额度" min-width="80"></el-table-column>
        <el-table-column prop="payedAccount" label="已付款金额" min-width="90"></el-table-column>
        <el-table-column                     label="操作" min-width="60">
          <template scope="scope">
            <el-button  @click.native.prevent="disabledRow(scope.row)" type="text" size="small" v-if="hasPublish(scope.row)" :disabled="hasDisabled(scope.row)">禁用
            </el-button>
            <el-button @click.native.prevent="deleteRow(scope.$index, scope.row)" type="text" size="small" v-else>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    <stepBtn :nextBtn="next" :successBtn="success" :prevBtn="prev" :saveBtn="save" :btnShow="btnShow" ></stepBtn>
  </div>
</template>
<script>
import {postLog} from 'api/common/index.js'
import stepBtn from '../stepButton'
import dialogProduct from './dialogProduct'
import {activityDetail} from 'api/activity'
export default {
  components: {
    dialogProduct, stepBtn
  },
  props: ['edit'],
  data () {
    return {
      show: false,
      btnShow: {                                                                                         //控制按钮展示
        next: false,
        prev: true,
        save: false,
        success: false
      },
      form: {
        productType: 'ANY',
        productIds: []
      },
      nowIndex: '',
      nextTap: '',
      prevTap: '',
      selectedProducts: []
    }
  },
  computed: {
    actTypeInfo () {
      return JSON.parse(sessionStorage.getItem('addActivityType'))
    },
    actType () {
      return JSON.parse(sessionStorage.getItem('actType')).text
    },
    status () {
      return sessionStorage.getItem('actStatus')
    }
  },
  created () {
    if (!this.edit) {
      this.checkStep();
    } else {
      this.btnShow.save = true
      this.btnShow.prev = false
    }
    this.getActivityDetail()
  },
  methods: {
    hasPublish (row) {
    //如果活动已经发布且这个卡券不是刚新增的就显示禁止按钮
      if (this.status === '1' && row.newAdd === undefined) {
        return true;
      } else {
        return false;
      }
    },
    hasDisabled (row) {
    // 如果这个活动已经禁止就置灰
      if (row.enable === 'NO') {
        return true
      } else {
        return false
      }
    },
    disabledRow (row) {
      let save = true;
      this.selectedProducts.forEach(element => {
        if (element.newAdd) {
          save = false;
          return
        }
      });
      if (save === false) {
        this.$alert('请先保存添加的卡券', '提示');
        return
      }
      this.$confirm('你确定要禁用该产品吗', '提示', {
      }).then(() => {
        this.$http.put('/api-active/v1/api/activityCenter/activity/disableProduct?activityId=' + JSON.parse(sessionStorage.getItem('activityId')) + '&productId=' + row.id)
            .then((response) => {
              let data = response.body;
              if (data.resultCode === '200') {
                this.getActivityDetail();
                this.$message({
                  type: 'info',
                  message: '页面已刷新'
                });
              }
            })
      })
    },
    deleteRow (index, row) {
      console.log(index)
      console.log(row)
      if (row.newAdd) {
        this.selectedProducts.splice(index, 1);
        return
      }
      let params = {activityId: JSON.parse(sessionStorage.getItem('activityId')), productId: row.id}
      this.$confirm('你确定要移除该产品吗', '提示', {
      }).then(() => {
        this.$http.put('/api-active/v1/api/activityCenter/activity/deleteProduct', params)
              .then((response) => {
                let data = response.body;
                if (data.resultCode === '200') {
                  this.$message({
                    type: 'info',
                    message: '页面已刷新'
                  });
                  this.getActivityDetail()
                }
              });
      })
    },
    async getActivityDetail () {
      try {
        let back = await activityDetail(sessionStorage.getItem('activityId'))
        back = back.data
        if (back.resultCode === '200') {
          console.log(back.result)
          if (back.result.products === null) {
            this.form.productType = 'ANY'
          } else {
            this.form.productType = 'ASSIGN'
            this.selectedProducts = back.result.products
          }
        } else {
          this.$alert(back.msg)
        }
      } catch (err) {
        this.$alert('请求失败', '提示')
      }
    },
    checkStep () {
      let stepArr = this.actTypeInfo.relatedSectionsArray;
      //现在处于第几步
      this.nowIndex = stepArr.indexOf('PRODUCT');
      //下一步
      let nextIndex = this.nowIndex + 1;
      let prevIndex = this.nowIndex - 1;
      // 如果这是最后一步了
      if (nextIndex === stepArr.length) {
        this.btnShow.success = true;
        this.prevTap = stepArr[prevIndex];
      } else {
        this.btnShow.next = true;
        this.nextTap = stepArr[nextIndex];
        this.prevTap = stepArr[prevIndex];
      }
    },
    getSelProductList (parm) {
      this.closeDialog()
      if (this.selectedProducts.length === 0) {
        this.selectedProducts = this.selectedProducts.concat(parm)
        return
      }
      let arr = [...this.selectedProducts];
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < parm.length; j++) {
          if (parm[j].id === arr[i].id) {
            this.$alert('产品' + parm[j].name + '已存在', '提示')
            parm.splice(j, 1);
          }
        }
      }
      this.selectedProducts = this.selectedProducts.concat(parm)
      this.closeDialog()
    },
    next () {
      this.submit('next')
    },
    prev () {
      this.$emit('changePageShow', this.prevTap, 'prev')
    },
    success () {
      this.submit('success')
    },
    save () {
      this.submit('save')
    },
    submit (type) {
      let arr = []
      this.selectedProducts.forEach(element => {
        if (element.newAdd) {
          arr.push(element.id)
        }
      });
      let parm = {
        activityId: sessionStorage.getItem('activityId'),
        productIds: arr,
        productType: this.form.productType
      }
      this.$http.put('/api-active/v1/api/activityCenter/activity/product', parm)
          .then((response) => {
            let data = response.body;
            if (data.resultCode === '200') {
              if (type === 'next') {
                this.$emit('changePageShow', this.nextTap)
              } else if (type === 'success') {
                this.$router.push({name: 'activityList'})
              } else if (type === 'save') {
                this.$alert('保存成功', '提示')
                this.getActivityDetail()
              }
              postLog('ACTIVITY_LIST_EDIT', parm.activityId, '', parm);
            } else {
              this.$alert('修改失败', '提示');
            }
          })
    },
    closeDialog () {
      this.show = false
    }
  }
}
</script>
<style lang="less" scoped>

</style>
